<template>
	<view class="pageBox-bgf7">
		<view class="listBox">
			<view class="title">账号数据</view>
			<uni-list>
				<uni-list-item @click="openSheet(0)" title="上传数据" rightText="上传本地数据" clickable></uni-list-item>
				<uni-list-item @click="openSheet(1)" title="读取数据" rightText="读数据到本地" clickable></uni-list-item>
				<uni-list-item @click="delData" title="删除数据" rightText="删除账号数据" clickable></uni-list-item>
			</uni-list>
			<view class="title">本地缓存</view>
			<uni-list>
				<uni-list-item @click="clearCache" title="清除缓存" :rightText="storeSize" clickable></uni-list-item>
			</uni-list>
		</view>
	</view>
	<uv-action-sheet ref="actionSheet" cancelText="取消" :actions="sheetList" @select="select" @close="close">
	</uv-action-sheet>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		unique
	} from '@/utils/common.js'
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	// import { onLoad, onShow } from  '@dcloudio/uni-app'
	import CrossFileReader from '@/utils/CrossFileReader.js'
	const db = uniCloud.database()
	const recordDB = db.collection('wallpaper-record')

	
	// 本地缓存相关
	// 判断kb是否达到mb
	function formatSize(kb) {
	  if (kb >= 1024) {
	    let mb = kb / 1024;
	    return `${mb.toFixed(2)} MB`;
	  }
	  return `${kb} KB`;
	}
	// 显示缓存大小
	const storeSize = ref('0 KB')
	const getStoreSize = () => {
		const res = uni.getStorageInfoSync()
		storeSize.value = `${formatSize(res.currentSize)}`
	}
	getStoreSize()
	// 清除本地缓存
	const clearCache = () => {
		uni.showModal({
			title: '提示',
			content: '是否清除所有本地缓存？（同时将退出登录）',
			confirmColor: 'red',
			success: (res) => {
				if (res.confirm) {
					uni.clearStorageSync()
					uni.showToast({
						title: '清除成功',
						icon: 'success'
					})
					getStoreSize()
					mutations.logout()
				} else {
					uni.showToast({
						title: '操作取消',
						icon: 'none',
					})
				}
	
			}
		})
	}
	
	// 删除数据
	const delData = () => {
		if(!store.hasLogin){
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			uni.navigateTo({
				url: '/pages/login/login/login-withpwd'
			})
			return
		}
		uni.showModal({
			title: '提示',
			content: '是否删除账号的所有数据？',
			success: async (res) => {
				if (res.confirm) {
					try {
						await recordDB.where(`user_id == '${store.userInfo._id}'`).remove()
						uni.showToast({
							title: '删除成功'
						})
					} catch (error) {
						uni.showToast({
							title: '删除失败',
							icon: 'error',
						})
					}
				}
			}
		})
	}

	// sheet组件
	const actionSheet = ref(null)
	const sheetList = ref([{
		name: '合并',
		value: 0
	}, {
		name: '覆盖',
		value: 1
	}, ])
	const open = () => {
		actionSheet.value.open();
	}
	const select = async (e) => {
		if(!store.hasLogin){
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			uni.navigateTo({
				url: '/pages/login/login/login-withpwd'
			})
			return
		}
		if(e.value == 1){
			const modalres = await uni.showModal({
				title: '提示',
				content: `是否覆盖${e.type == 0 ? '云端' : '本地'}数据？`
			})
			if(modalres.cancel) {
				uni.showToast({
					title: '操作取消',
					icon: 'none',
				})
				return
			}
		}
		// console.log('选中该项：', e);
		// type  0 上传	1 读取
		// value 0 合并	1 覆盖 
		// 本地数据
		let historyImageArr = unique(uni.getStorageSync('historyInfo_img'), '_id')
		let downloadImageArr = unique(uni.getStorageSync('downloadInfo_img'), '_id')
		let collectImageArr = uni.getStorageSync('collectInfo_img')
		// 上传
		if (e.type == 0) {
			uni.showLoading({
			  mask: true
			})
			try {
				// 获取云端数据
				const res = await recordDB.where(`user_id == '${store.userInfo._id}'`).get({
					getOne: true
				})
				const recordData = res.result.data // obj
				if (!recordData) {
					// 不存在直接添加 不涉及覆盖合并
					await recordDB.add({
						imgCollectRecord: collectImageArr,
						imgHistoryRecord: historyImageArr,
						imgDownloadRecord: downloadImageArr
					})
					return
				}
				let newData = {}
				if (e.value == 0) {
					// 合并
					newData = {
						imgCollectRecord: unique([...recordData.imgCollectRecord, ...collectImageArr], '_id'),
						imgHistoryRecord: unique([...recordData.imgHistoryRecord, ...historyImageArr], '_id'),
						imgDownloadRecord: unique([...recordData.imgDownloadRecord, ...downloadImageArr],
							'_id'),
						timestamp: Date.now()
					}
				} else if (e.value == 1) {
					// 覆盖
					newData = {
						imgCollectRecord: collectImageArr,
						imgHistoryRecord: historyImageArr,
						imgDownloadRecord: downloadImageArr,
						timestamp: Date.now()
					}
				}
				await recordDB.where(`user_id == '${store.userInfo._id}'`).update(newData)
				uni.showToast({
					title: '上传成功'
				})
			} catch (error) {
				uni.showToast({
					icon: 'error',
					title: '上传失败'
				})

			} finally {

			}
		}
		// 下载
		else if (e.type == 1) {
			uni.showLoading({
			  mask: true
			})
			try {
				// 获取云端数据
				const res = await recordDB.where(`user_id == '${store.userInfo._id}'`).get({
					getOne: true
				})
				const recordData = res.result.data // obj
				if (!recordData) {
					// 不存在
					uni.showToast({
						title: '云端无数据',
						icon:'none'
					})
					return
				}
				let newData = {}
				if (e.value == 0) {
					// 合并
					uni.setStorageSync('collectInfo_img', unique([...recordData.imgCollectRecord, ...collectImageArr], '_id'))
					uni.setStorageSync('downloadInfo_img', unique([...recordData.imgDownloadRecord, ...downloadImageArr], '_id'))
					uni.setStorageSync('historyInfo_img',  unique([...recordData.imgHistoryRecord, ...historyImageArr], '_id'))
					
				} else if (e.value == 1) {
					// 覆盖
					uni.setStorageSync('collectInfo_img', recordData.imgCollectRecord)
					uni.setStorageSync('downloadInfo_img', recordData.imgDownloadRecord)
					uni.setStorageSync('historyInfo_img',  recordData.imgHistoryRecord)
				}
				uni.showToast({
					title: '读取成功'
				})
				getStoreSize()
			} catch (error) {
				uni.showToast({
					icon: 'error',
					title: '读取失败'
				})

			} finally {

			}
		}

	}



	const close = () => {
		setTimeout(() => {
			sheetList.value = [{
				name: '合并',
				value: 0
			}, {
				name: '覆盖',
				value: 1
			}]
		}, 300)




	}
	const openSheet = (type) => {
		if (type == 0) {
			sheetList.value.map(item => {
				item.name =  item.name  + '上传到云端'
				item.type = 0
			})
		} else if (type == 1) {
			sheetList.value.map(item => {
				item.name =  item.name  + '读取到本地'
				item.type = 1
			})
		}
		actionSheet.value.open()
	}
</script>

<style scoped lang="scss">
	:deep() {
		uni-page-wrapper {
			background-color: #f7f7f7;

		}
		.uni-list-item {
			height: 120rpx;
		}
	}

	.title {
		margin: 20rpx 0 20rpx 30rpx;
		color: #999;
		font-size: 32rpx;

	}

	.listBox {
		border-radius: 20rpx;
		overflow: hidden;

	}
</style>